package com.alliky.main.ui;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alliky.core.base.BaseActivity;
import com.alliky.core.router.RoutePath;
import com.alliky.core.base.AppManager;
import com.alliky.main.R;
import com.alliky.main.R2;
import com.alliky.main.mvp.contract.MainContract;
import com.alliky.main.mvp.presenter.MainPresenter;
import com.tamsiree.rxkit.view.RxToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

@Route(path = RoutePath.Main.MAIN_ACTIVITY)
public class MainBaseActivity extends BaseActivity<MainPresenter> implements MainContract.View {

    @BindView(R2.id.pager_bottom_tab)
    PageNavigationView mPageNavigationView;

    List<Fragment> mFragments;

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    public Object setLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void onInitView(@Nullable Bundle savedInstanceState) {

        initFragment();
        initBottomTab();
    }

    private void initFragment() {
        //ARouter拿到多Fragment(这里需要通过ARouter获取，不能直接new,因为在组件独立运行时，宿主app是没有依赖其他组件，所以new不到其他组件的Fragment)
        Fragment homeFragment = (Fragment) ARouter.getInstance().build(RoutePath.Home.HOME_FRAGMENT).navigation();
        Fragment classifyFragment = (Fragment) ARouter.getInstance().build(RoutePath.Classify.CLASSIFY_FRAGMENT).navigation();
        Fragment cartFragment = (Fragment) ARouter.getInstance().build(RoutePath.Cart.CART_FRAGMENT).navigation();
        Fragment myFragment = (Fragment) ARouter.getInstance().build(RoutePath.User.MY_FRAGMENT).navigation();

        mFragments = new ArrayList<>();
        mFragments.add(homeFragment);
        mFragments.add(classifyFragment);
        mFragments.add(cartFragment);
        mFragments.add(myFragment);
        if (homeFragment != null) {
            //默认选中第一个
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.frameLayout, homeFragment);
            transaction.commitAllowingStateLoss();

        }
    }

    private void initBottomTab() {
        NavigationController navigationController = mPageNavigationView.material()
                .addItem(R.mipmap.icon_tab_home, "首页", ContextCompat.getColor(getContext(), R.color.deepskyblue))
                .addItem(R.mipmap.icon_tab_classify, "分类", ContextCompat.getColor(getContext(), R.color.deepskyblue))
                .addItem(R.mipmap.icon_tab_cart, "购物车", ContextCompat.getColor(getContext(), R.color.deepskyblue))
                .addItem(R.mipmap.icon_tab_my, "我的", ContextCompat.getColor(getContext(), R.color.deepskyblue))
                .build();
        //底部按钮的点击事件监听
        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                Fragment currentFragment = mFragments.get(index);
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                if (currentFragment != null) {
//                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//                    transaction.replace(R.id.frameLayout, currentFragment);
//                    transaction.commitAllowingStateLoss();

                    for (Fragment fragment : mFragments) {
                        transaction.hide(fragment);
                    }

                    addFragment(currentFragment, transaction);
                }
            }

            @Override
            public void onRepeat(int index) {
            }
        });
    }

    private void addFragment(Fragment fragment, FragmentTransaction transaction) {
        if (!fragment.isAdded()) {
            transaction.add(R.id.frameLayout, fragment);
        }
        transaction.show(fragment);
        transaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mFragments.size() > 0) {
            for (Fragment fragment : mFragments) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    /**
     * 监听Back键按下事件,方法2:
     * 注意:
     * 返回值表示:是否能完全处理该事件
     * 在此处返回false,所以会继续传播该事件.
     * 在具体项目中此处的返回值视情况而定.
     */
    private static long lastTime;

    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
            lastTime = currentTime;// 更新lastTime
            RxToast.normal("再按一次退出程序");
        } else {
            // 两次按键小于2秒时，退出应用
            AppManager.getInstance().AppExit();
        }
    }
}
